
import React, { useEffect, useState } from 'react';
import { PlusOutlined, } from '@ant-design/icons';
import { Upload, message } from 'antd';
import { downloadFileFromOSS, upFileToOSS } from '@/ui/xx-AliyunOSSUpload/client/AliOss';
import { uuid } from '@/utils';



/**
 * @description 单照片上传 适用于Form.Item 上传照片，回调为阿里云返回的照片name值  阿里云对象储存 简单上传 
 * @param {*} param0 
 * @returns 
 */
const XxUploadPhoto = ({
    accept = 'image/png,image/jpg,image/jpeg',
    maxCount = 5,
    multiple = true,
    value,
    onChange
}) => {

    const [fileList, setFileList] = useState([]);

    const customRequest = async ({ file, onSuccess, onError }) => {
        let metaData = {
            fileName: file.name,
            busiId: `contractEntity.contractCode`,
            busiType: 'OBC'
        }
        let res = await upFileToOSS(file, metaData);
        if (res.url) {
            onSuccess({
                url: res.url,
                uid: uuid(),
                name: res.name
            });
            onChange && onChange(res.name)
        } else {
            message.error("图片上传失败：")
            onError()
        }
    }

    const initImage = async (fileName) => {
        let metaData = {
            fileName: fileName,
            busiId: `contractEntity.contractCode`,
            busiType: 'OBC'
        }
        let res = await downloadFileFromOSS(metaData);
        if (res.status === "0000") {
            setFileList([{
                url: res?.data?.url,
                uid: uuid(),
                size: res?.data?.size
            }])
        } else {
            message.error("图片加载失败")
        }
    }




    useEffect(() => {
        if (value) {
            initImage(value);
        }
    }, [])


    const uploadChange = ({ file, fileList: newFileList }) => {
        setFileList(newFileList)
    }




    return (
        <>

            <Upload
                accept={accept}
                action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                listType="picture-card"
                showUploadList={{ showPreviewIcon: false }}
                maxCount={maxCount}
                customRequest={customRequest}
                onChange={uploadChange}
                fileList={fileList}
                multiple={multiple}
            >
                {
                    fileList.length > 0 ? null : <div>
                        <PlusOutlined />
                        <div
                            style={{
                                marginTop: 8,
                            }}
                        >
                            上传
                        </div>
                    </div>
                }

            </Upload>
        </>
    )
}

export default XxUploadPhoto;